﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using BrainTechLLC;
using ImageAppDataModels;
using System.Windows.Threading;
using System.Windows.Input;
using ImageAppViewModels;
using BrainTechLLC.WPF;


namespace WpfImageDuplicates
{
    /// <summary>
    /// Interaction logic for TopCommandBar.xaml
    /// </summary>
    public partial class TopCommandBar : UserControl
    {
        public SimpleDispatcherTimer _timer;
        public SimpleDispatcherTimer _updateCollectionSize;
        public int _lastCollectionSize = 0;
        public event EventHandler<ObjectEventArgsNonRef<double, double>> ChangeThumbnailSize;

        public static readonly DependencyProperty SettingsViewModelProperty =
            DependencyProperty.Register("SettingsViewModel", typeof(SettingsViewModel), typeof(TopCommandBar), new PropertyMetadata(null, OnSettingsViewModelPropertyChanged));

        public SettingsViewModel SettingsViewModel
        {
            get { return (SettingsViewModel)GetValue(SettingsViewModelProperty); }
            set { SetValue(SettingsViewModelProperty, value); }
        }

        private static void OnSettingsViewModelPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TopCommandBar source = d as TopCommandBar;
            SettingsViewModel vNew = e.NewValue as SettingsViewModel;
            SettingsViewModel vOld = e.OldValue as SettingsViewModel;
            source.UpdateSettingsViewModel(vNew, vOld);
        }

        private void UpdateSettingsViewModel(SettingsViewModel viewModel, SettingsViewModel viewModelOld)
        {
            if (viewModel == viewModelOld)
                return;

            SettingsViewModel = viewModel;

            // Let the UI bind to the view-model.
            this.DataContext = SettingsViewModel;
        }

        public TopCommandBar()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(TopCommandBar_Loaded);
            _timer = new SimpleDispatcherTimer(600, timer => Timer_Tick(timer));
            _timer.Start();
            _updateCollectionSize = new SimpleDispatcherTimer(200, timer => UpdateCollectionSize_Tick(timer));
            _updateCollectionSize.Start();
        }

        RunInitializationResult UpdateCollectionSize_Tick(SimpleDispatcherTimer timer)
        {
            var itemCount = 0;
            Window1.MainWindow.CollectionViews.ForEach(o => itemCount += o.Rectangles.Count + o.ThumbsHandler._thumbsByFileName.Count);
            if (_lastCollectionSize == itemCount)
            {
                if (timer._doneNothingCount > 10)
                {
                    if (timer._doneNothingCount > 50)
                    {
                        timer.TimerInterval = 3000;
                    }
                    else
                    {
                        timer.TimerInterval = 1000;
                    }
                }
                return RunInitializationResult.DidntDoAnything;
            }
            timer.TimerInterval = 200;
            _lastCollectionSize = itemCount;
            listItemCount.Text = itemCount.ToString();
            return RunInitializationResult.DidSomething;
        }

        RunInitializationResult Timer_Tick(SimpleDispatcherTimer timer)
        {
            bool didSomething = false;

            if (timer._doneNothingCount > 20)
            {
                timer.TimerInterval = 3000;
            }
            else
            {
                timer.TimerInterval = 600;
            }

            if (Window1.MainWindow.CollectionViews.ItemSelectionChanged)
            {
                Window1.MainWindow.CollectionViews.ItemSelectionChanged = false;
                int counter = 0;
                Window1.MainWindow.CollectionViews.ForEach(o => counter += o.lstItems.SelectedItems.Count);
                listSelected.Text = counter.ToString();
                didSomething = true;
            }
            if (Window1.MainWindow.CollectionViews.ViewModelCollectionChanged)
            {
                Window1.MainWindow.CollectionViews.ViewModelCollectionChanged = false;
                int counter = 0;
                if (Window1.MainWindow._CollectionViews != null)
                {
                    Window1.MainWindow.CollectionViews.ForEach(o =>
                    {
                        if (o.FileImageCollectionViewModel != null) { counter += o.FileImageCollectionViewModel.Count; }
                    });
                }
                if (!didSomething)
                {
                    int oldCount = 0;
                    if (int.TryParse(listTotal.Text, out oldCount))
                    {
                        if (oldCount == counter)
                        {
                            return RunInitializationResult.DidntDoAnything;
                        }
                    }
                }
                listTotal.Text = counter.ToString();
                didSomething = true;
            }

            return didSomething ? RunInitializationResult.DidSomething : RunInitializationResult.DidntDoAnything;
        }

        void TopCommandBar_Loaded(object sender, RoutedEventArgs e)
        {
            if (Settings.Values != null)
            {
                thumbWidthHeight.SetLastWidthHeight((int)Settings.Values.ThumbWidth, (int)Settings.Values.ThumbHeight);
            }
        }

        private void widthHeight_ChangeSize(object sender, ObjectEventArgsNonRef<double, double> e)
        {
            Settings.Values.SetThumbWidthAndHeight(e.obj1, e.obj2);

            if (ChangeThumbnailSize != null)
                ChangeThumbnailSize(this, new ObjectEventArgsNonRef<double, double>(e.obj1, e.obj2));
        }

        private void btnSetThumbWidthHeight_Click(object sender, RoutedEventArgs e)
        {
            var pt = Mouse.GetPosition(this);
            border1.Margin = new Thickness(pt.X - 40, pt.Y + 6, 0, 0);
            popup.IsOpen = !popup.IsOpen;
            if (filterPopup.IsOpen)
            {
                Dispatcher.BeginInvoke(() => thumbWidthHeight.txtWidth.Focus(), DispatcherPriority.Render);
            }
        }

        private void btnSelectSort_Click(object sender, RoutedEventArgs e)
        {
            var pt = Mouse.GetPosition(this);
            border2.Margin = new Thickness(pt.X - 40, pt.Y + 6, 0, 0);
            sortPopup.IsOpen = !sortPopup.IsOpen;
        }

        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            var pt = Mouse.GetPosition(this);
            border3.Margin = new Thickness(pt.X - 40, pt.Y + 6, 0, 0);
            filterPopup.IsOpen = !filterPopup.IsOpen;
            if (filterPopup.IsOpen)
            {
                Dispatcher.BeginInvoke(() => fileNameFilter.txtFileNameFilter.Focus(), DispatcherPriority.Render);
            }
        }

        private void fileNameFilter_RequestDone(object sender, EventArgs e)
        {
            filterPopup.IsOpen = false;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
            Settings.Values.TopCommandBarVisibile = false;
        }
    }
}
